package cn.xuexiluxian.open.framework.interceptor;

import cn.xuexiluxian.open.common.annotation.Log;
import cn.xuexiluxian.open.common.enums.BusinessType;
import cn.xuexiluxian.open.common.enums.ResultStatusCodeEnum;
import cn.xuexiluxian.open.common.exception.SystemException;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@Slf4j
@Component
public class DemonstrationInterceptor implements HandlerInterceptor{
	@Override
	public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) {
		String referer = request.getHeader("referer");
		if(referer != null && (referer.startsWith("http://demo.open.xuexiluxian.cn/") || referer.startsWith("https://demo.open.xuexiluxian.cn/"))) {
			if(handler instanceof HandlerMethod) {
				HandlerMethod handlerMethod = (HandlerMethod) handler;
				Log annotation = handlerMethod.getMethodAnnotation(Log.class);
				if(annotation == null) {
					return Boolean.TRUE;
				}
				BusinessType businessType = annotation.businessType();
				if(!BusinessType.SELECT.equals(businessType) && !BusinessType.FORCE.equals(businessType)) {
					throw new SystemException(ResultStatusCodeEnum.HTTP_FORBIDDEN, "演示环境不允许操作");
				}
			}
		}
		return Boolean.TRUE;
	}
	
	@Override
	public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler,
			ModelAndView modelAndView) throws Exception {
		HandlerInterceptor.super.postHandle(request, response, handler, modelAndView);
	}
	
	@Override
	public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex)
			throws Exception {
		HandlerInterceptor.super.afterCompletion(request, response, handler, ex);
	}
	
}
